package com.eascs.web.o2o.web.reward.service.impl;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

import javax.inject.Inject;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.eascs.app.dao.PageResult;
import com.eascs.app.dao.SqlPageQuery;
import com.eascs.app.log.Logger;
import com.eascs.app.log.LoggerFactory;
import com.eascs.common.util.StringUtil;
import com.eascs.web.o2o.web.reward.dao.BaseDao;
import com.eascs.web.o2o.web.reward.entity.RiskAmountQueryForm;
import com.eascs.web.o2o.web.reward.entity.RiskAmountVo;
import com.eascs.web.o2o.web.reward.service.RiskAmountService;
import com.eascs.web.sso.User;
import com.eascs.web.sso.UserHolder;

/**
 * @author:hzp
 * @date:2018年4月3日
*/
@Service
public class RiskAmountServiceImpl implements RiskAmountService{

	private static Logger log = LoggerFactory.getLogger(RiskAmountServiceImpl.class);
	
	@Inject
	BaseDao baseDao;
	
	@Override
	public PageResult<Object[]> getRiskAmount(RiskAmountQueryForm entity) {
		String sql = "select t.t_month,t.province_name,t.user_no,t.user_name,t.bill_code,t.loaner_name,t.operator_name,t.loan_amount,t.loan_date,t.expire_date,t.royalty_coefficient,t.extract_ratio,t.extract_amount,t.user_bill_relation from dm_reward_risk_amount_extract t where /**DATA_PERMISSION(t.ltd)**/ 1=1 ";
		SqlPageQuery<Object[]> sqlPageQuery = new SqlPageQuery<>(Object[].class, entity.getPageSize(), entity.getShowPage());
		StringBuffer querySql = new StringBuffer();
		querySql.append(sql); 
		querySql.append(" AND t.t_month = ?");
		
		sqlPageQuery.addParam(entity.getMonth());
		
		if(!StringUtil.isEmpty(entity.getProvince())){
			querySql.append(" AND t.province_name = ?");
			sqlPageQuery.addParam(entity.getProvince());
		}
		System.out.println(JSON.toJSONString(entity));
		System.out.println(querySql.toString());
		sqlPageQuery.setQuerySql(querySql.toString());
		return baseDao.findDataWithPage(sqlPageQuery);
	}

	@Override
	public PageResult<Object[]> downRiskAmount(RiskAmountQueryForm entity) {
		String sql = "select t.t_month,t.province_code,t.province_name,t.user_no,t.user_code,t.user_name,t.bill_code,t.loaner_name,t.operator_no,t.operator_name,t.loan_amount,t.loan_term,t.loan_date,t.expire_date,t.royalty_coefficient,t.extract_ratio,t.extract_amount,t.user_bill_relation ,t.ltd,t.ltd_code,t.ltd_name from dm_reward_risk_amount_extract t where 1=1 ";
		SqlPageQuery<Object[]> sqlPageQuery = new SqlPageQuery<>(Object[].class, entity.getPageSize(), entity.getShowPage());
		StringBuffer querySql = new StringBuffer();
		querySql.append(sql); 
		querySql.append(" AND t.t_month = ?");
		sqlPageQuery.addParam(entity.getMonth());
		/*if(!StringUtil.isEmpty(entity.getProvince())){
			querySql.append(" AND t.province_name = ?");
			sqlPageQuery.addParam(entity.getProvince());
		}*/
		sqlPageQuery.setQuerySql(querySql.toString());
		return baseDao.findDataWithPage(sqlPageQuery);
	}

	@Override
	@Transactional("transactionManagerDbForReward")
	public void addRiskAmountList(List<List<Object>> result) {
		User user=UserHolder.getUser();
		//删除当前月份前一个月的所有数据
		baseDao.executeSql(" delete from dm_reward_risk_amount_extract where  t_month = DATE_FORMAT(DATE_SUB(now(),INTERVAL 1 month),'%Y-%m')");
		
		//将excel中的数据导入到数据库中
		if(result!=null&&result.size()>0){
			for (int i = 0; i < result.size(); i++) {
				@SuppressWarnings({ "unchecked", "rawtypes" })
				List<Object> list = (List) result.get(i);
				for(int j=0;j<list.size();j++){
					if(list.get(j) == null)
						list.set(j, "0");
				}
				RiskAmountVo vo = new RiskAmountVo();
				vo.settMonth(list.get(0).toString());
				vo.setProvinceCode(list.get(1).toString());
				vo.setProvinceName(list.get(2).toString());
				vo.setUserNo(list.get(3).toString());
				vo.setUserCode(list.get(4).toString());
				vo.setUserName(list.get(5).toString());
				vo.setBillCode(list.get(6).toString());
				vo.setLoanerName(list.get(7).toString());
				vo.setOperatorNo(Integer.valueOf(list.get(8).toString()));
				vo.setOperatorName(list.get(9).toString());
				vo.setLoanAmount(BigDecimal.valueOf(Double.valueOf(list.get(10).toString())));
				vo.setLoanTerm(Integer.valueOf(list.get(11).toString()));
				vo.setLoanDate((Date)list.get(12));
				vo.setExpireDate((Date)list.get(13));
				vo.setRoyaltyCoefficient(BigDecimal.valueOf(Double.valueOf(list.get(14).toString())));
				vo.setExtractRatio(BigDecimal.valueOf(Double.valueOf(list.get(15).toString())));
				vo.setExtractAmount(BigDecimal.valueOf(Double.valueOf(list.get(16).toString())));
				vo.setUserBillRelation(list.get(17).toString());
				vo.setLtd(list.get(18).toString());
				vo.setLtdCode(list.get(19).toString());
				vo.setLtdName(list.get(20).toString());
				vo.setIsLock("N");
				vo.setCreateUser(user.getCname());
				vo.setCreateDate(new Date());
				vo.setUpdateUser(user.getCname());
				vo.setUpdateDate(new Date());
				vo.setConfirmUser(user.getCname());
				vo.setConfirmDate(new Date());
				baseDao.saveEntity(vo);
		    	}				
		}else{
			log.error("导入的数据为空，事务回滚");
			throw new RuntimeException("导入的数据为空，请重新导入！");
		}
	}

}
